package ru.tulupov.scheduledrunner.command;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ru.tulupov.scheduledrunner.command.impl.RunCommand;
import ru.tulupov.scheduledrunner.util.Utils;

/**
 * @author <a href="mailto:zhekka3@gmail.com">Eugene Tulupov</a>
 */
public class CommandFactory {
	private Map<String, Class<? extends Command>> commands;

	private static class CommandFactoryHolder {
		public static CommandFactory INSTANCE = new CommandFactory();
	}

	public static CommandFactory getInstance() {
		return CommandFactoryHolder.INSTANCE;
	}

	@SuppressWarnings("unchecked")
	private CommandFactory() {
		commands = new HashMap<String, Class<? extends Command>>();

		List<Class<?>> classes = Utils
				.getClassesForPackage("ru.tulupov.scheduledrunner.command.impl");
		for (Class<?> clazz : classes) {
			CommandAnnotation annotation = clazz
					.getAnnotation(CommandAnnotation.class);

			if (annotation != null) {
				commands.put(annotation.name(),
						(Class<? extends Command>) clazz);
			}
		}
	}

	public Command get(String name) {
		Command command = null;
		try {
			Class<? extends Command> clazz = commands.get(name);
			if (clazz != null) {
				command = clazz.newInstance();
			}
		} catch (Exception e) {

		}
		return command;
	}
}
